/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.dolphinscheduler.alert.runner;

import org.apache.dolphinscheduler.alert.utils.Constants;
import org.apache.dolphinscheduler.alert.utils.PropertyUtils;
import org.apache.dolphinscheduler.common.enums.AlertStatus;
import org.apache.dolphinscheduler.common.plugin.PluginManager;
import org.apache.dolphinscheduler.common.utils.StringUtils;
import org.apache.dolphinscheduler.dao.AlertDao;
import org.apache.dolphinscheduler.dao.entity.Alert;
import org.apache.dolphinscheduler.dao.entity.User;
import org.apache.dolphinscheduler.plugin.api.AlertPlugin;
import org.apache.dolphinscheduler.plugin.model.AlertData;
import org.apache.dolphinscheduler.plugin.model.AlertInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * alert sender 邮件发送
 */
public class AlertSender {

    private static final Logger logger = LoggerFactory.getLogger(AlertSender.class);

    private List<Alert> alertList; // 邮件发送列表
    private AlertDao alertDao;
    private PluginManager pluginManager;

    public AlertSender() {}

    /**
     * @param alertList 状态为0的alert任务
     * @param alertDao  操作alert的dao
     * @param pluginManager 插件的plugin 默认有email的插件
     */
    public AlertSender(List<Alert> alertList, AlertDao alertDao, PluginManager pluginManager) {
        super();
        this.alertList = alertList;
        this.alertDao = alertDao;
        this.pluginManager = pluginManager;
    }

    /**
     * 发送邮件
     */
    public void run() {
        List<User> users;
        Map<String, Object> retMaps = null;
        for (Alert alert : alertList) {
            /**
             * 查找该组的user
             * SELECT u.* FROM t_ds_relation_user_alertgroup g_u JOIN t_ds_user u on g_u.user_id = u.id
             *  WHERE g_u.alertgroup_id = #{alertgroupId}
              */
            users = alertDao.listUserByAlertgroupId(alert.getAlertGroupId());
            // receiving group list
            List<String> receviersList = new ArrayList<>();
            // 添加t_ds_user表的email
            for (User user : users) {
                receviersList.add(user.getEmail());
            }
            /**
             * 封装相关的邮件数据
             */
            AlertData alertData = new AlertData();
            alertData.setId(alert.getId())
                    .setAlertGroupId(alert.getAlertGroupId())
                    .setContent(alert.getContent())
                    .setLog(alert.getLog())
                    .setReceivers(alert.getReceivers())
                    .setReceiversCc(alert.getReceiversCc())
                    .setShowType(alert.getShowType().getDescp())
                    .setTitle(alert.getTitle());//邮件的标题

            AlertInfo alertInfo = new AlertInfo();
            alertInfo.setAlertData(alertData);

            alertInfo.addProp("receivers", receviersList);
            /**
             * 这里面获取的就是emailPlugin,在启动类的时候添加的,Constants.PLUGIN_DEFAULT_EMAIL是对应的id
             */
            AlertPlugin emailPlugin = pluginManager.findOne(Constants.PLUGIN_DEFAULT_EMAIL);
            retMaps = emailPlugin.process(alertInfo);

            if (retMaps == null) {
                alertDao.updateAlert(AlertStatus.EXECUTION_FAILURE, "alert send email error", alert.getId());
                logger.info("alert send  email error : return value is null");
            } else if (!Boolean.parseBoolean(String.valueOf(retMaps.get(Constants.STATUS)))) {
                alertDao.updateAlert(AlertStatus.EXECUTION_FAILURE, String.valueOf(retMaps.get(Constants.MESSAGE)), alert.getId());
                logger.info("alert send email error : {}", retMaps.get(Constants.MESSAGE));
            } else {
                alertDao.updateAlert(AlertStatus.EXECUTION_SUCCESS, (String) retMaps.get(Constants.MESSAGE), alert.getId());
                logger.info("alert send email success");
            }

            /**
             * hrt 增加发送短信的逻辑,异步处理,在AlertManager封装了userId在title字段
             */
            try{
                if(PropertyUtils.getBoolean("alert.sms")){
                    logger.info("alert sms  start send");
                    String userId=alert.getTitle().split(":")[0];
                    String phone=alertDao.queryPhone(userId);
                    if(StringUtils.isNotBlank(phone)){
                        // 重新封装title 给手机发送
                        alertData.setTitle(phone);
                        alertInfo.setAlertData(alertData);

                        logger.info("load sms plugin start");
                        AlertPlugin smsPlugin = pluginManager.findOne("sms");
                        logger.info("load sms plugin finish");

                        smsPlugin.process(alertInfo);
                        logger.info("alert sms  send success");
                    }else{
                        logger.info("phone is empty , can't send sms");
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

}
